// Package route @author dingrui @since 2021/11/24
package route

import (
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/recover"

	"github.com/bannirui/mini-prize/web/application"
	"github.com/bannirui/mini-prize/web/controller"
	"github.com/bannirui/mini-prize/web/middleware"
	"github.com/bannirui/mini-prize/web/util/response"
)

//
//  Configure
//  @Description: 配置路由
//  @param application
//
func Configure(app *application.App) {
	var (
		party iris.Party
	)
	party = preConfigure(app)
	// 逐个添加路由
	controller.AdminBlackIpRouter(party)
	controller.AdminCouponRouter(party)
	controller.AdminGiftRouter(party)
	controller.AdminResultRouter(party)
}

//
//  preConfigure
//  @Description: 前置配置
//  @param application
//  @return party
//
func preConfigure(app *application.App) (party iris.Party) {
	var (
		loggerHandler iris.Handler // 自定义的日志处理器
	)
	app.Logger().SetLevel("debug")
	loggerHandler, _ = middleware.NewRequestLogger()
	app.Use(
		recover.New(), // 恢复
		loggerHandler, // 日志
	)
	// 定义错误处理
	app.OnErrorCode(iris.StatusNotFound, loggerHandler, func(ctx iris.Context) {
		response.Error(ctx, iris.StatusNotFound, response.CODE_NOTFOUNT)
	})
	app.OnErrorCode(iris.StatusInternalServerError, loggerHandler, func(ctx iris.Context) {
		response.Error(ctx, iris.StatusInternalServerError, response.CODE_FAILUR)
	})
	// 设置跨域
	crs := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowedHeaders: []string{"*"},
	})
	// 项目根域名
	party = app.Party("/api/mini-prize", crs).AllowMethods(iris.MethodOptions)
	return party
}
